<?php
// +----------------------------------------------------------------------
// | Desc: [ Better-充值审核 ]
// +----------------------------------------------------------------------
// | Author: huangzhen_20210406
// +----------------------------------------------------------------------

namespace app\index\model;

use app\api\controller\EmailSend;
use think\facade\Db;
use app\index\model\UserLog as userLogModel;
use app\common\model\Common;

class FundCheck extends Common
{

    //---------------------------------------------前端---------------------------------------------------------------
    /**
     * @param $user_id
     * @param $data
     * @return bool
     */
    public function dataSave($user_id ,$data)
    {
        $blog       = true;
        $fund_type  = $data['fund_type'];
        unset($data['fund_type']);
        Db::startTrans();
        try{
            $check_num  = getRandNumber();
            $amount     = 0;
            $ctime      = getUtcTime();
            $desc       = "";
            $trn        = '';
            switch ($fund_type){
                case 'fund_wire':
                    $check_num  = 'W' . $check_num;
                    $amount     = $data['wire_amount'];
                    $desc       = "Wire Transfer Deposit {$check_num}";
                    $trn        = $data['bank_trn'];
                    Db::name('fund_check_wire')->save([
                        'check_num'         => $check_num,
                        'wire_date'         => $data['wire_date'],
                        'wire_amount'       => $amount,
                        'account_name'      => $data['account_name'],
                        'account_number'    => $data['account_number'],
                        'bank_area_id'      => $data['bank_area_id'],
                        'bank_name_id'      => $data['bank_name_id'],
                        'bank_trn'          => $trn,
                        'upload_img'        => $data['upload_img'],
                        'overseas_charges'  => $data['overseas_charges'],
                        'ctime'             => $ctime
                    ]);
                    break;
                case 'fund_ach':
                    $check_num = 'A' . $check_num;
                    $amount    = $data['transfer_amount'];
                    $desc      = "ACH Transfer Deposit {$check_num}";
                    $trn       = $data['bank_trn'];
                    Db::name('fund_check_ach')->save([
                        'check_num'         => $check_num,
                        'transfer_date'     => $data['transfer_date'],
                        'transfer_amount'   => $amount,
                        'account_name'      => $data['account_name'],
                        'bank_trn'          => $trn,
                        'upload_img'        => $data['upload_img'],
                        'ctime'             => $ctime
                    ]);
                    break;
                case 'fund_zelle':
                    $check_num = 'Z' . $check_num;
                    $amount    = $data['amount'];
                    $desc      = "Zelle Deposit {$check_num}";
                    $trn       = $data['trn'];
                    Db::name('fund_check_zelle')->save([
                        'check_num'             => $check_num,
                        'date_sent'             => $data['date_sent'],
                        'sender_account_type'   => $data['sender_account_type'],
                        'first_name'            => $data['first_name'],
                        'last_name'             => $data['last_name'],
                        'sender_business_name'  => $data['sender_business_name'],
                        'amount'                => $amount,
                        'trn'                   => $data['trn'],
                        'upload_img'            => $data['upload_img'],
                        'ctime'                 => $ctime
                    ]);
                    break;
            }
            Db::name('fund_check')->save([
                'user_id'       => $user_id,
                'check_num'     => $check_num,
                'amount'        => $amount,
                'desc'          => $desc,
                'ctime'         => $ctime,
                'trn'           => $trn
            ]);

            //发送邮件通知管理员
//            $username = session('user.username');
//            EmailSend::sendEmail('user_fund' , [
//                'email'     => getSetting('fund_email_send'),
//                'desc'      => "{$username} Funding : $ {$amount}"
//            ]);
            //记录用户操作日志
            userLogModel::setLog($user_id , 'user fund' , ["amount:$ {$amount}" , "check_num:{$check_num}"]);
            Db::commit();
        } catch (\Exception $e) {
            $blog       = false;
            Db::rollback();
        }

        return $blog;
    }

    public function dataSaveNew($user_id ,$data)
    {
        $blog       = true;
        $pay_type   = $data['pay_type'];   //1-支付宝.2-微信
        $date       = $data['date'];
        $amount     = $data['amount'];
        $name       = $data['name'];
        $upload_img = $data['upload_img'];
        $check_num  = getRandNumber();
        $ctime      = getUtcTime();
        $desc       = 'Funding';
        Db::startTrans();
        try{
            switch ($pay_type){
                case 1:
                    $check_num  = 'A' . $check_num;
                    Db::name('fund_check_alipay')->save([
                        'check_num'         => $check_num,
                        'name'              => $name,
                        'date'              => $date,
                        'amount'            => $amount,
                        'upload_img'        => $upload_img,
                        'ctime'             => $ctime
                    ]);
                    $desc = '支付宝充值';
                    break;
                case 2:
                    $check_num  = 'W' . $check_num;
                    Db::name('fund_check_wechat')->save([
                        'check_num'         => $check_num,
                        'name'              => $name,
                        'date'              => $date,
                        'amount'            => $amount,
                        'upload_img'        => $upload_img,
                        'ctime'             => $ctime
                    ]);
                    $desc = '微信充值';
                    break;
            }
            Db::name('fund_check')->save([
                'user_id'       => $user_id,
                'check_num'     => $check_num,
                'amount'        => $amount,
                'ctime'         => $ctime,
                'desc'          => $desc,
                'pay_type'      => $pay_type
            ]);

            //记录用户操作日志
            userLogModel::setLog($user_id , 'user fund' , ["amount:$ {$amount}" , "check_num:{$check_num}"]);
            Db::commit();
        } catch (\Exception $e) {
            Db::name('api_error')->save([
                'user_id'       => $user_id,
                'amount'        => $amount,
                'amount_bank'   => $amount,
                'type'          => 'fund_' . $pay_type,
                'data_param'    => $e->getMessage(),
                'ctime'         => getUtcTime()
            ]);
            $blog       = false;
            Db::rollback();
        }
        if($blog){
            //发送邮件通知管理员
            $username = session('user.username');
            EmailSend::sendEmail('user_fund' , [
                'email'     => getSetting('fund_email_send'),
                'desc'      => "{$username} Funding : $ {$amount}"
            ]);
        }

        return $blog;
    }

    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableData($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        $where[] = ['user_id', '=', $post['user_id']];
        if(isset($post['status']) && strlen($post['status'])>0){
            $where[] = ['check_status', '=', $post['status']];
        }
        if(isset($post['type']) && strlen($post['type'])>0){
            $where[] = ['type', '=', $post['type']];
        }
        if(isset($post['desc']) && !empty($post['desc'])){
            $where[] = ['msg', '=', $post['desc']];
        }
        if(isset($post['stime']) && !empty($post['stime'])){
            $start_time = strtotime($post['stime'] . " 00:00:00") - 13*60*60;
            $end_time   = strtotime((empty($post['ltime'])?"2023-12-31":$post['ltime'])  . " 23:59:59") - 13*60*60;
            $where[] = ['ctime', 'between', "{$start_time},{$end_time}"];
        }
        $list = Db::name('fund_check')
            ->order('ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    /**
     * 会员到首页显示充值列表(只显示成功的)
     * @param $post
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function indexHomeTable($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        $where[] = ['user_id', '=', $post['user_id']];
        $where[] = ['check_status', '=', 1];
        $list = Db::name('fund_check')
            ->where($where)
            ->order('utime desc')
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }
}